package com.flower.gateway;

import com.alibaba.fastjson.JSONObject;
import com.common.baseModel.JsonResult;
import com.common.utils.CloudConstant;
import com.common.utils.ServletUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Base64Utils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @ClassName GatewayFilter
 * @Description 判断请求是否经过网关
 * @Author 吃麻椒的花酱
 * @Date 2022/4/4 0:07
 * @Version 1.0
 */

@WebFilter(filterName = "GatewayFilter",urlPatterns = {"/**"})
public class GatewayFilter implements Filter {

    @Resource
    CloudSecurityProperties cloudSecurityProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest requrst=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        if (!cloudSecurityProperties.getOnlyFetchByGateway()) {
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String token = requrst.getHeader(CloudConstant.GATEWAY_TOKEN_HEADER);
        String gatewayToken = new String(Base64Utils.encode(CloudConstant.GATEWAY_TOKEN_VALUE.getBytes()));
        if (StringUtils.equals(gatewayToken, token)) {
            filterChain.doFilter(servletRequest,servletResponse);
        } else {
            JsonResult<Object> res = JsonResult.createError("must go through the gateway");
            //将对象转为string字符串
            ServletUtils.sendString(response,new String(JSONObject.toJSONString(res).getBytes()));
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
